<template>
  <div>
    <el-card>
      <el-form class="userformtop">
        <el-form-item label="用户">
          <el-input placeholder="请输入用户名" v-model="keyword" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" :disabled="keyword ? false : true" @click="tapsoso">搜索</el-button>
          <!-- <el-button type="primary" size="default">重置</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0;">
      <el-button type="primary" size="default" @click="tapadduser">增加用户</el-button>
      <el-button type="primary" size="default" :disabled="Selectdlt.length ? false : true"
        @click="deleteselectuser">批量删除</el-button>
      <el-table style="margin: 10px 0;" @selection-change="handleSelectionChange" :data="userArr" border>
        <el-table-column type="selection">
        </el-table-column>
        <el-table-column type="index" label="#" width="80px">
        </el-table-column>
        <el-table-column label="id" prop="id" width="140px">
        </el-table-column>
        <el-table-column label="用户名字" prop="name" width="140px">
        </el-table-column>
        <el-table-column label="用户名称" prop="username" width="140px">
        </el-table-column>
        <el-table-column label="用户角色" width="140px">
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="140px">
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" width="140px">
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button type="primary" size="small" @click="allocation(row)">分配角色</el-button>
            <el-button type="primary" size="small" @click="updateUser(row)">编辑</el-button>
            <!-- <el-button type="primary" size="default" >删除</el-button> -->
            <el-popconfirm :title="`确定要删除 ${row.username} 吗?`" icon="DeleteFilled" icon-color="#f56c6c"
              @confirm="deleteUser(row.id)">
              <template #reference>
                <el-button type="danger" size="small" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>
      <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]"
        @current-change="getHassSpu" @size-change="changesize" :background="true"
        layout="prev, pager,next, jumper,->, sizes,total,  " :total="total" />
    </el-card>
    <el-drawer v-model="drawer" :title="userParams.id ? '修改用户' : '增加用户'">
      <el-form :model="userParams" :rules="rulesForm" ref="userForm">
        <el-form-item label="用户姓名" prop="username">
          <el-input placeholder="请填写用户名字" v-model="userParams.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input placeholder="请填写用户昵称" v-model="userParams.name"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input placeholder="请填写用户密码" v-model="userParams.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="rePassword" v-if="userParams.id == 0">
          <el-input v-model="userParams.rePassword" type="password" show-password placeholder="请确认密码" prefix-icon="Lock"
            clearable></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="tapdrawershow">取消</el-button>
          <el-button type="primary" size="default" @click="tapsubmit">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <el-drawer v-model="drawer1" title="分配角色用户">
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <div>
            <el-checkbox @change="handleCheckArrChange" v-model="checkarr"
              :indeterminate="isIndeterminate">全选</el-checkbox>

          </div>
          <el-checkbox-group v-model="userRole" @change="handleCheckedRoleChange">
            <el-checkbox v-for="role in allRole" :key="role.id" :label="role">{{ role.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" icon="Select" @click="setRoleSave">确定</el-button>
        <el-button icon="CloseBold" @click="drawer1 = false">取消</el-button>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { getuser, addsave, update, addupdate, toAssign, doAssignRole, remove, batchRemove } from '@/api/acl/user.js'
import { ref, onMounted, nextTick } from 'vue'
let total = ref(0)
let pageNo = ref(1)
let limit = ref(3)
let keyword = ref('')
let userArr = ref([])
let drawer = ref(false)
let drawer1 = ref(false)
let Selectdlt = ref([])
// 全部权限
let allRole = ref([])
// 用户已选择权限
let userRole = ref([])
let userParams = ref({
  id: 0,
  username: '',
  name: '',
  password: '',
  rePassword: ''
})
// 收集用户信息
let userForm = ref(null)
// 自定义校验用户名
const validatorUsername = (rule, value, callback) => {
  // 用户名|昵称长度最少五位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名称长度最少五位'))
  }
}
const validatorName = (rule, value, callback) => {
  // 用户名|昵称长度最少五位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称长度最少五位'))
  }
}
const validatorPassword = (rule, value, callback) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户密码长度最少六位'))
  }
}
const validatorRePassword = (rule, value, callback) => {
  if (value === userParams.value.password) {
    callback()
  } else {
    callback(new Error('两次密码不一致'))
  }
}
// 表单规则校验对象
let rulesForm = ref({
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
  rePassword: [{ required: true, trigger: 'change', validator: validatorRePassword }]
})
onMounted(() => {
  getHasUser()
})
const getHasUser = (page = 1) => {
  pageNo.value = page
  getuser(pageNo.value, limit.value, keyword.value).then(res => {
    console.log(res);
    if (res.code == 200) {
      userArr.value = res.data.records
      total.value = res.data.total
    }
  })
}
const tapdrawershow = () => {
  drawer.value = false
}
let getHassSpu = () => {
  getHasUser(pageNo.value)
}
let changesize = () => {
  getHasUser()
}
// 增加
const tapadduser = (row) => {
  // 每次打开清空
  Object.assign(userParams.value, {
    id: 0,
    username: '',
    name: '',
    password: '',
    rePassword: ''
  })
  // 清空上一次表单提示信息
  nextTick(() => {
    userForm.value?.clearValidate()
  })
  drawer.value = true
}
// 确认
const tapsubmit = () => {
  console.log(userParams.value);
  if (userParams.value.id == 0) {
    addsave(userParams.value).then(res => {
      console.log(res);
      if (res.code == 200) {
        getHasUser()
        drawer.value = false
        ElNotification({
          message: '成功',
          type: 'success',
          title: '添加成功'
        })
      } else {
        ElMessage.error(res.message)
      }
    })
  } else {
    update(userParams.value).then(res => {
      console.log(res);
      if (res.code == 200) {
        console.log(res);
        getHasUser()
        drawer.value = false
        ElNotification({
          message: '成功',
          type: 'success',
          title: '修改成功'
        })
      } else {
        ElMessage.error(res.message)
      }
    })
  }

}
// 编辑
const updateUser = (row) => {
  // 清空上一次表单提示信息
  nextTick(() => {
    userForm.value?.clearValidate()
  })
  // 存储收集已有的账号信息
  Object.assign(userParams.value, row)
  drawer.value = true
}
// 分配
const allocation = (row) => {
  toAssign(row.id).then(res => {
    console.log(res);
    if (res.code !== 200) return ElMessage.error(res.message)
    // 存取当前自己
    userRole.value = res.data.assignRoles
    // 存取全部职位
    allRole.value = res.data.allRolesList
  })
  Object.assign(userParams.value, row)
  drawer1.value = true
}
// 全选复选框
let checkArr = ref(false)
let isIndeterminate = ref(false)
const handleCheckArrChange = (val) => {
  console.log(val);
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
const handleCheckedRoleChange = (value) => {
  console.log(1111, value);
  const checkedCount = value.length
  checkArr.value = checkedCount === allRole.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRole.value.length

}
const setRoleSave = async () => {
  console.log(11212);
  // 收集处理数据
  let data = {
    userId: (userParams.value.id),
    roleIdList: userRole.value.map((item) => (item.id))
  }
  const res = await doAssignRole(data)
  if (res.code !== 200) return ElMessage.error(res.message)
  ElMessage.success(res.message)
  getHasUser(pageNo.value)
  drawer1.value = false
}
// 删除单个
const deleteUser = async (id) => {
  let res = await remove(id)
  if (res.code !== 200) return ElMessage.error(res.message)
  ElMessage.success(res.message)
  // 删除完检查当前页面是否还有数据没有跳转到第一页
  getHasUser(userArr.value.length > 1 ? pageNo.value : 1)
}
const handleSelectionChange = (val) => {
  Selectdlt.value = val

}
// 批量删除
const deleteselectuser = () => {
  let selectidarr = Selectdlt.value.map(item => item.id)
  batchRemove(selectidarr).then(res => {
    if (res.code !== 200) return ElMessage.error(res.message)
    ElMessage.success(res.message)
    // 删除完检查当前页面是否还有数据没有跳转到第一页
    getHasUser(userArr.value.length > 1 ? pageNo.value : 1)
  })
}
const tapsoso = () => {
  getHasUser()
  keyword.value = ''
}
</script>
<style scoped lang="scss">
.userformtop {
  display: flex;
  justify-content: space-between;
}
</style>